<template>
    <div>
        <div class="top-panel">
            <el-card>
                <el-form :model="searchForm" label-width="70px" label-position="right">
                    <el-row>
                        <el-col :span="5">
                            <el-form-item label="名称">
                                <el-input class="password-input" v-model="searchForm.nameFuzzy" clearable
                                    placeholder="支持模糊搜索" @keyup.enter.native="loadDataList"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="描述">
                                <el-input class="password-input" v-model="searchForm.descriptionFuzzy" clearable
                                    placeholder="支持模糊搜索" @keyup.enter.native="loadDataList"></el-input>
                            </el-form-item>
                        </el-col>

                        <el-col :span="4" :style="{ paddingLeft: '10px' }">
                            <el-button type="success" @click="loadDataList()">查询</el-button>
                            <el-button type="info" @click="reset()">重置</el-button>
                        </el-col>
                    </el-row>
                </el-form>
            </el-card>
        </div>
        <el-card class="table-data-card">
            <template #header>
                <span>菜品列表</span>
            </template>
            <Table ref="tableInfoRef" :columns="columns" :fetch="loadDataList" :dataSource="tableData"
                :options="tableOptions" :extHeight="tableOptions.extHeight" @row-click="handleRowClick">
                <template #operation="{ index, row }">
                    <div class="row-op-panel">
                        <a class="a-link" href="javascript:void(0)" @click.prevent="openAddOrUpdata(row)">审核</a>
                        <a class="a-link" href="javascript:void(0)" @click.prevent="delDishesBtn(row.id)">删除</a>
                    </div>
                </template>
            </Table>
        </el-card>

        <FormDialog ref="formDialogRef" :title="dialogTitle" :form-model="formModel" :rules="rules" cancel-text="取消"
            confirm-text="审核" @submit="handleSubmit" @closed="resetTempFlavor">
            <el-form-item label="菜品分类" prop="categoryId">
                <el-select v-model="formModel.categoryId" placeholder="请选择分类" disabled>
                    <el-option v-for="(item, index) in categoriesData" :label="item.name" :value="item.id"
                        :key="index"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="菜品名称" prop="name">
                <el-input v-model="formModel.name" placeholder="请输入菜品名称" disabled/>
            </el-form-item>

            <el-form-item label="口味">
                <el-button @click="addFlavors()">＋</el-button>
            </el-form-item>

            <el-form-item label="描述" prop="description">
                <el-input type="textarea" v-model="formModel.description" placeholder="请输入描述" :rows="3" disabled/>
            </el-form-item>

            <el-form-item label="排序" prop="sortOrder">
                <el-input-number v-model="formModel.sortOrder" :min="0" :step="1" placeholder="请输入排序值" disabled/>
            </el-form-item>

            <el-form-item label="原价" prop="originalPrice">
                <el-input-number v-model="formModel.originalPrice" :precision="2" :step="0.1" :max="9999" :min="0" disabled/>
            </el-form-item>

            <el-form-item label="现价" prop="price">
                <el-input-number v-model="formModel.price" :precision="2" :step="0.1" :max="9999" :min="0" disabled/>
            </el-form-item>

            <el-form-item label="库存" prop="stock">
                <el-input-number v-model="formModel.stock" :min="0" :max="999999" disabled/>
            </el-form-item>

            <el-form-item label="图片">
                <el-upload action="#" list-type="picture-card" :auto-upload="false" v-model:file-list="fileList"
                    :disabled="true">
                    <el-icon>
                        <Plus />
                    </el-icon>

                    <template #file="{ file }">
                        <div>
                            <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                            <span class="el-upload-list__item-actions">
                                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                                    <el-icon>
                                        <ZoomIn />
                                    </el-icon>
                                </span>
                            </span>
                        </div>
                    </template>
                </el-upload>

                <el-dialog v-model="dialogVisible">
                    <img style="width: 100%;" :src="dialogImageUrl" alt="Preview Image" />
                </el-dialog>
            </el-form-item>

        </FormDialog>


        <!-- 口味选择 -->
        <FormDialog ref="formDialogFlaRef" :title="dialogFlaTitle" :form-model="tempFlavorModel"
            @submit="handleFlaSubmit">
            <el-form-item label="口味名称" prop="name">
                <el-input v-model="tempFlavorModel.name" placeholder="请输入口味名称" disabled/>
            </el-form-item>

            <el-form-item label="口味值" prop="values">
                <div v-for="(val, index) in tempFlavorModel.values" :key="index"
                    style="display:flex; align-items:center; margin-bottom:6px;">
                    <el-input v-model="tempFlavorModel.values[index]" placeholder="请输入口味值" style="flex:1;" disabled/>
                </div>
            </el-form-item>

            <el-form-item label="状态" prop="isRequired">
                <el-select v-model="tempFlavorModel.isRequired" placeholder="是否必选" disabled>
                    <el-option label="可选" :value="0"></el-option>
                    <el-option label="必选" :value="1"></el-option>
                </el-select>
            </el-form-item>
        </FormDialog>

        <!-- 审核表单 -->
        <FormDialog ref="formDialogAudRef" :title="dialogAudTitle" :form-model="AuditModel" :rules="AuditRules"
            @submit="handleAuditSubmit">
            <el-form-item label="审核状态" prop="auditStatus">
                <el-select v-model="AuditModel.auditStatus" placeholder="选择审核状态">
                    <el-option label="通过" :value="1"></el-option>
                    <el-option label="不通过" :value="2"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="审核备注" prop="auditRemark">
                <el-input type="textarea" v-model="AuditModel.auditRemark" placeholder="请输入审核备注" :rows="3" />
            </el-form-item>
        </FormDialog>

    </div>
</template>
<script setup>

import FormDialog from '@/components/FormDialog.vue';
import { getCurrentInstance, nextTick, ref } from 'vue';
import { Plus, ZoomIn } from '@element-plus/icons-vue'


const { proxy } = getCurrentInstance()

const searchForm = ref({
    auditStatus: 0,
})
const tableData = ref({})
// 分类数据列表
const categoriesData = ref([])

// 审核列表数据
const AuditModel = ref({
    auditStatus: 1,
})

// 临时口味表单数据
const tempFlavorModel = ref({
    name: '',
    isRequired: 0,
    values: []
})

const tableOptions = ref({
    extHeight: 125
})

const api = {
    // 获取分类列表
    getCategories: '/tuanCategories/loadDataList',
    // 获取菜品列表
    loadDataList: '/tuanDishes/loadDataList',
    // 获取审核信息
    getAudit: '/tuanDishesAudit/getAudit',
    // 审核
    approve: '/tuanDishesAudit/approve',
     // 删除菜品
    delDishes: '/tuanDishes/delDishes',
}

const columns = [
    {
        label: "商家",
        prop: "merchantId",
    },
    {
        label: "分类名称",
        prop: "nameCateName",
    },
    {
        label: "菜品名称",
        prop: "name",
    },
    {
        label: "菜品描述",
        prop: "description",
    },
    {
        label: "菜品价格",
        prop: "price",
    },
    {
        label: "原价",
        prop: "originalPrice",
    },
    {
        label: "状态",
        prop: "statusName",
    },
    {
        label: "库存",
        prop: "stock",
    },
    {
        label: "审核状态",
        prop: "auditStatusName",
    },
    {
        label: "创建时间",
        prop: "createdAt",
    },
    {
        label: "更新时间",
        prop: "updatedAt",
    },
    {
        width: 150,
        label: "操作",
        scopedSlots: "operation"
    }
]

const AuditRules = {
  auditStatus: [
    { required: true, message: '请选择审核状态', trigger: 'change' }
  ],
  auditRemark: [
    {
      validator: (rule, value, callback) => {
        if (AuditModel.value.auditStatus === 2 && !value) {
          callback(new Error('请输入审核备注'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const resetTempFlavor = () => {
    tempFlavorModel.value = {
        name: '',
        isRequired: 0,
        id: null,
        dishId: null,
        values: []
    };
};

const getCategories = async () => {
    let params = {
        pageNo: tableData.value.pageNo,
        pageSize: 9999,
    }

    Object.assign(params, searchForm.value)
    let result = await proxy.Request({
        url: api.getCategories,
        params,
    })

    if (!result) {
        return
    }
    Object.assign(categoriesData.value, result.data.list)
}

// 菜品列表数据
const loadDataList = async () => {
    let params = {
        pageNo: tableData.value.pageNo,
        pageSize: tableData.value.pageSize,
    }

    Object.assign(params, searchForm.value)
    let result = await proxy.Request({
        url: api.loadDataList,
        params,
    })

    if (!result) {
        return
    }

    Object.assign(tableData.value, result.data)

    console.log(result);

}

const tableInfoRef = ref()

// 重置方法
const reset = () => {
    searchForm.value = {
        nameFuzzy: '',
        descriptionFuzzy: '',
        auditStatus: 0
    }
    loadDataList()
}

// 新增修改操作
const formDialogRef = ref(null)
const formDialogFlaRef = ref(null)
const formDialogAudRef = ref(null)
const dialogTitle = ref('')
const dialogFlaTitle = ref('')
const dialogAudTitle = ref('')


const formModel = ref({
    flavors: {
        values: []
    }
})

// 审核按钮
const openAddOrUpdata = async (row) => {
    // 获取分类
    getCategories()
    dialogTitle.value = '审核菜品'
    formModel.value = { ...row }
    tempFlavorModel.value = {
        name: row.dishFlavors.name,
        id: row.dishFlavors.id,
        dishId: row.dishFlavors.dishId,
        isRequired: 0,
        values: row.dishFlavors.values
    };

    // 获取审核信息
    let result = await proxy.Request({
        url: api.getAudit,
        params: {
            id: row.id
        }
    })

    if (result.code === 200 && result.data != null) {
        AuditModel.value = result.data
        if (AuditModel.value.auditStatus === 0) {
            AuditModel.value.auditStatus = 1
        }
    }

    AuditModel.value.dishId = row.id

    formModel.value.flavors = JSON.stringify(tempFlavorModel.value);


    // 图片赋值
    fileList.value = row.attachment?.map(img => ({
        id: img.id,       // 数据库已有 ID
        url: `data:${img.fileType};base64,${img.fileUrl}`, // base64
        raw: null         // 原文件为 null，表示未修改
    })) || []

    nextTick(() => formDialogRef.value.open('bounce'))
}

// 审核口味
const addFlavors = () => {
    dialogFlaTitle.value = '审核口味'
    nextTick(() => formDialogFlaRef.value.open('bounce'))

}

const handleFlaSubmit = async () => {
    // 保存到菜品表单
    formModel.value.flavors = JSON.stringify(tempFlavorModel.value);
    formDialogFlaRef.value.close()
}

// 提交审核数据
const handleAuditSubmit = async() => {
    let params = Object.assign(AuditModel.value);
    let result = await proxy.Request({
        url: api.approve,
        params,
    })
    if (result && result.code === 200) {
        proxy.$message.success("审核成功");
        formDialogAudRef.value.close();
        formDialogRef.value.close();
        loadDataList()
    }
    
}

const handleSubmit = async () => {
    dialogAudTitle.value = '审核'
    nextTick(() => formDialogAudRef.value.open('bounce'))
}

const fileList = ref([])
const dialogVisible = ref(false)
const dialogImageUrl = ref('')

const handlePictureCardPreview = (file) => {
    dialogImageUrl.value = file.url
    dialogVisible.value = true
}

// 删除菜品
const delDishesBtn = async (id) => {
    proxy.Confirm('确定删除菜品吗？', async () => {
        let result = await proxy.Request({
            url: api.delDishes,
            params: {
                id
            }
        })
        if (result != null && result.code === 200) {
            proxy.$message.success('删除成功')
            loadDataList()
        }
    })
}

</script>

<style lang="scss" scoped>
.detail-tree-panel {
    height: calc(100vh - 273px);
    overflow: auto;
    width: 100%;
}
</style>